import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

/**
 * @Author: zhouge
 * @Description: 通讯录界面
 * @Date: Created in 15:42 2020-07-12
 * @Modified By:
 **/
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../model/contacts.dart' show ContactsPageData, Contact;
import '../config.dart';

class _ContactItem extends StatelessWidget {
  // 构造函数
  _ContactItem({
    @required this.avatar,
    @required this.title,
    this.grouptitle,
    this.onPressed,
  });

  final Contact _contact = ContactsPageData.mock().contacts[0];
  final String avatar;
  final String title;
  final String grouptitle;
  final VoidCallback onPressed; // flutter 提供的回调函数

  static const double MARGIN_VARTICAL = 10.0;
  static const double BUTTON_HEIGHT = 48.0;
  static const double GROUP_TITLE_HEGIGHT = 24.0;

  //计算控件的高度
  static double _height(bool _hasGroupTitle) {
    final _buttonHeight = MARGIN_VARTICAL * 2 +
        Constants.ContactAvatarSize +
        Constants.DividerWidth;
    if (_hasGroupTitle) {
      return _buttonHeight + GROUP_TITLE_HEGIGHT;
    }
    return _buttonHeight;
  }

  //判断资源来源地
  bool get _isAvatarFromNet {
    return this.avatar.startsWith('http') || this.avatar.startsWith('https');
  }

  @override
  Widget build(BuildContext context) {
    // 判断素材来源于网络还是本地
    Widget _avatarIcon;
    if (_isAvatarFromNet) {
      _avatarIcon = Image.network(
        avatar,
        width: Constants.ContactAvatarSize,
        height: Constants.ContactAvatarSize,
      );
    } else {
      _avatarIcon = Image.asset(
        avatar,
        width: Constants.ContactAvatarSize,
        height: Constants.ContactAvatarSize,
      );
    }

    //列表项主体部分
    Widget _button = Container(
      margin: const EdgeInsets.symmetric(horizontal: 16.0),
      //padding: const EdgeInsets.symmetric(vertical: 10.0),
      padding: const EdgeInsets.symmetric(vertical: MARGIN_VARTICAL),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                  width: Constants.DividerWidth,
                  color: Color(AppColors.DividerColor)))),
      child: Row(
        children: <Widget>[
          _avatarIcon,
          SizedBox(width: 10.0),
          Text(title),
        ],
      ),
    );

    //分组标签
    Widget _itemBody;
    if (this.grouptitle != null) {
      _itemBody = Column(
        children: <Widget>[
          Container(
            height: GROUP_TITLE_HEGIGHT,
            padding: EdgeInsets.only(left: 16.0, right: 16.0),
            color: Color(AppColors.ContactGroupTitleBg),
            alignment: Alignment.centerLeft,
            child: Text(
              this.grouptitle,
              style: AppStyles.GroupTitleItemTextStyle,
            ),
          ),
          _button,
        ],
      );
    } else {
      _itemBody = _button;
    }

    return _itemBody;
  }
}

// 快速查询的列表结构
const INDEX_BAR_WORDS = [
  "↑",
  "☆", "A",
  "B", "C", "D", "E",
  "F", "G", "H", "I", "J",
  "K", "L", "M", "N",
  "O", "P", "Q", "R",
  "S", "T", "U", "V",
  "W", "X", "Y", "Z"
];

class ContactsPage extends StatefulWidget {
  //默认索引为透明色
  Color _indexBarBg = Colors.transparent;
  // 默认的当前字母
  String _currentLetter = '';
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  //列表控件
  ScrollController _scrollController;
  final List<Contact> _contacts = [];
  final ContactsPageData data = ContactsPageData.mock();

  //符号位置
  final Map _letterPosMap = {INDEX_BAR_WORDS[0]: 0.0};

  final List<_ContactItem> _funtionButtons = [
    _ContactItem(
      avatar: 'assets/images/ic_new_friend.png',
      title: '新的朋友',
      onPressed: () {
        print('添加新朋友');
      },
    ),
    _ContactItem(
      avatar: 'assets/images/ic_group_chat.png',
      title: '群聊',
      onPressed: () {
        print('建立群聊');
      },
    ),
    _ContactItem(
      avatar: 'assets/images/ic_tag.png',
      title: '标签',
      onPressed: () {
        print('点击标签');
      },
    ),
    _ContactItem(
      avatar: 'assets/images/ic_public_account.png',
      title: '公总号',
      onPressed: () {
        print('公总号');
      },
    ),
  ];

  // 初始化千万不要写错了
  @override
  void initState() {
    super.initState();
    //链式调用数据
    _contacts..addAll(data.contacts)..addAll(data.contacts)..addAll(data.contacts);
    //排序的实现
    _contacts.sort((Contact a, Contact b) => a.nameIndexLetter.compareTo(b.nameIndexLetter));
    // 初始化控制
    _scrollController = new ScrollController();

    //计算用于 IndexBar 进行定位的关键通讯录列表项的位置
    var _totalPos = _funtionButtons.length * _ContactItem._height(false);
    for (int i = 1; i < _contacts.length; i++) {
      bool _hasGroupTitle = true;
      if (i > 0 && _contacts[i].nameIndexLetter.compareTo(_contacts[i - 1].nameIndexLetter) == 0) {
        _hasGroupTitle = false;
      }
      if (_hasGroupTitle) {
        _letterPosMap[_contacts[i].nameIndexLetter] = _totalPos;
      }
      _totalPos += _ContactItem._height(_hasGroupTitle);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
  }

  // 通过函数，获取字母。
  String getLetter(BuildContext context, double tileHeight, Offset globalPos) {
    RenderBox _box = context.findRenderObject();
    var local = _box.globalToLocal(globalPos);
    int index = (local.dy ~/ tileHeight).clamp(0, INDEX_BAR_WORDS.length - 1);
    return INDEX_BAR_WORDS[index]; // 返回字母
  }

  // 字母索引调转的函数
  void _jumpToIndex(String letter) {
    if (_letterPosMap.isNotEmpty) {
      final _pos = _letterPosMap[letter];
      if (_pos != null) {
        _scrollController.animateTo(_pos,
            curve: Curves.easeInOut, duration: Duration(milliseconds: 200));
      }
    }
  }

  // 新建一个索引控件
  Widget _buildIndexBar(BuildContext context, BoxConstraints constraints) {
    final List<Widget> _letters = INDEX_BAR_WORDS.map((String word) {
      return Expanded(
        child: Text(word),
      );
    }).toList();

    final double _totalHeight = constraints.biggest.height;
    final double _tileHeight = _totalHeight / _letters.length;
    return GestureDetector(
      onVerticalDragDown: (DragDownDetails details) {
        setState(() {
          widget._indexBarBg = Colors.black26;
          widget._currentLetter = getLetter(context, _tileHeight, details.globalPosition);
          _jumpToIndex(widget._currentLetter);
        });
      },

      // 取消按钮
      onVerticalDragCancel: () {
        setState(() {
          widget._indexBarBg = Colors.transparent;
          widget._currentLetter = null;
        });
      },

      onVerticalDragEnd: (DragEndDetails details) {
        setState(() {
          widget._indexBarBg = Colors.transparent;
          widget._currentLetter = null;
        });
      },
      // 按钮 按着上下滚动
      onVerticalDragUpdate: (DragUpdateDetails details) {
        setState(() {
          widget._indexBarBg = Colors.black26;
          widget._currentLetter = getLetter(context, _tileHeight, details.globalPosition);
          _jumpToIndex(widget._currentLetter);
        });
      },

      child: Column(
        children: _letters,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> _body = [
      ListView.builder(
        controller: _scrollController,
        itemBuilder: (BuildContext context, int index) {
          // 索引的返回
          if (index < _funtionButtons.length) {
//              _totalPos += _funtionButtons[index]._height(false);
            return _funtionButtons[index];
          }
          int _contactIndex = index - _funtionButtons.length;
          bool _isGroupTitle = true;
          Contact _contact = _contacts[_contactIndex];
          if (_contactIndex >= 1 && _contact.nameIndexLetter == _contacts[_contactIndex - 1].nameIndexLetter) {
            _isGroupTitle = false;
          }

          return _ContactItem(
            avatar: _contact.avatar,
            title: _contact.name,
            grouptitle: _isGroupTitle ? _contact.nameIndexLetter : null,
          );
        },
        itemCount: _contacts.length + _funtionButtons.length,
      ),

      //右侧快速索引的运用方式
      Positioned(
        width: Constants.IndexBarWidth,
        right: 10.0,
        top: 0.0,
        bottom: 0.0,
        child: Container(
            // 容器的颜色，初始化的时候要给
            color: widget._indexBarBg,
            child: LayoutBuilder(builder: _buildIndexBar,)
        ),
      ),
    ];

    // 不为空，并且要值，才会显示中间的圆圈
    if (widget._currentLetter != null && widget._currentLetter.isNotEmpty) {
      _body.add(
        Center(
            child: Container(
              width: Constants.IndexLetterBoxSize,
              height: Constants.IndexLetterBoxSize,
              decoration: BoxDecoration(
              color: AppColors.IndexLetterBoxBg,
              borderRadius: BorderRadius.all(
                  Radius.circular(Constants.IndexLetterBoxRadius))),
              child: Center(
                child: Text(widget._currentLetter,
                style: AppStyles.IndexLetterBoxTextStyle),
          ),
        )),
      );
    }
    // Stack 为绝对布局
    return Stack(
      children: _body,
    );
  }
}
